from sqlalchemy import TEXT, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from dc_shop.core.models.enums.order import DeliveryMethod, OrderStatus

from .base import TimedBaseModel


class Order(TimedBaseModel):
    __tablename__ = "order"
    __mapper_args__ = {"eager_defaults": True}

    id: Mapped[int] = mapped_column(primary_key=True)
    status: Mapped[OrderStatus] = mapped_column(server_default="created")
    order_lines = relationship("OrderLine", backref="order", passive_deletes="all")
    summ: Mapped[float] = mapped_column(nullable=False)
    comment: Mapped[str | None] = mapped_column(TEXT)
    user = relationship("User", back_populates="orders")
    user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
    payment_method = relationship("PaymentDetails", back_populates="orders")
    payment_method_id: Mapped[int | None] = mapped_column(ForeignKey("payment_details.id"))
    delivery_method: Mapped[DeliveryMethod] = mapped_column(server_default="courier")
    shipping_address: Mapped[str | None] = mapped_column(TEXT)
    user_phone: Mapped[str | None]
    shop = relationship("Shop", back_populates="orders")
    shop_id: Mapped[int] = mapped_column(ForeignKey("shop.id"))
    promocode = relationship("Promocode", back_populates="orders")
    promocode_id: Mapped[int | None] = mapped_column(ForeignKey("promocode.id"))
    tracking_link: Mapped[str | None]
    tickets = relationship("Ticket", back_populates="order")
    invoice_screenshot_path: Mapped[str | None]

    def __repr__(self):
        return f"<Заказ №{self.id} {self.created_at}>"

    def __str__(self):
        return self.__repr__()
